package com.xnf.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xnf.model.common.dtos.ResponseResult;
import com.xnf.model.common.enums.AppHttpCodeEnum;
import com.xnf.model.search.dtos.UserSearchDto;
import com.xnf.model.search.pojos.ApAssociateWords;
import com.xnf.search.mapper.ApAssociateWordsMapper;
import com.xnf.search.model.Trie;
import com.xnf.search.service.ApAssociateWordsService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xnf on 2022/3/17.
 */
@Service
public class ApAssociateWordsServiceImpl extends ServiceImpl<ApAssociateWordsMapper,ApAssociateWords> implements ApAssociateWordsService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult search(UserSearchDto dto) {
        //1.检查参数
        if (dto.getPageSize() > 50) {
            return ResponseResult.okResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        IPage pageParam = new Page<>(0,dto.getPageSize());
        IPage<ApAssociateWords> page = page(pageParam, Wrappers.<ApAssociateWords>lambdaQuery().like(ApAssociateWords::getAssociateWords, dto.getSearchWords()));
        return ResponseResult.okResult(page.getRecords());
    }

    @Override
    public ResponseResult searchV2(UserSearchDto userSearchDto) {
        String assoStr = redisTemplate.boundValueOps("associate_list").get();
        List<ApAssociateWords> list = null;
        if (StringUtils.isNotEmpty(assoStr)){
            list = JSON.parseArray(assoStr,ApAssociateWords.class);
        }else{
            list = list();
            redisTemplate.boundValueOps("associate_list").set(JSON.toJSONString(list));
        }
        Trie trie = new Trie();
        for (ApAssociateWords apAssociateWords : list){
            trie.insert(apAssociateWords.getAssociateWords());
        }
        List<String> ret = trie.startWith(userSearchDto.getSearchWords());
        List<ApAssociateWords> resultList  = new ArrayList<>();
        for (String s : ret){
            ApAssociateWords aaw = new ApAssociateWords();
            aaw.setAssociateWords(s);
            resultList.add(aaw);
        }
        return ResponseResult.okResult(resultList);
    }
}
